const router = require('koa-router')()
const formidable = require("formidable");
const jwt = require("jsonwebtoken")
const mykey = "djxdjxdjx"
const path = require('path')
const fs = require('fs');
const dirPath = path.join(path.resolve(__dirname, '../'), 'public/images')

// 提交需求
router.post('/pull', async (ctx, next) => {
  // 接收发布物品的信息,将文字插入到数据库中etimage
  let info = JSON.parse(ctx.request.body)
  // console.log(info.text);
  let message = {};
  let timer = new Date;
  var hour = timer.getHours(); //获取当前小时
  var minute = timer.getMinutes(); //获取当前分钟
  var second = timer.getSeconds(); //获取当前秒
  // 明天找一个时间试一下
  let hours = hour < 10 ? "0" + hour : hour
  let minutes = minute < 10 ? "0" + minute : minute
  let seconds = second < 10 ? "0" + second : second
  let Date1 = hours + ":" + minutes + ":" + seconds
  // console.log(Date1);
  // console.log(hours,minutes,seconds);
  let sql = 'insert into request (requestText,requestDate,userName,avatarUrl) value (?,?,?,?)'
  let result = await ctx.db.EXCUTE(sql, [info.text, Date1, info.name, info.avatar]);
  // console.log(result);
  if (result.length > 0) {
    message = { code: 200, msg: "成功" }
  }
  else {
    message = { code: 400, mgs: '失败' }
  }
  ctx.body = message
})
// 显示需求列表
router.post('/request', async (ctx, next) => {
  // let info = JSON.parse(ctx.request.body)
  let sql = 'select * from request'
  let message = {}
  let text = [];
  let result = []
  let resultrequest = await ctx.db.EXCUTE(sql)
  for (var i = 0; i < resultrequest.length; i++) {
    // console.log(resultrequest.length);
    text[i] = resultrequest[i].requestText
    // console.log(text[i]);
    let sql1 = 'select * from img where text=?'
    let resultrequest1 = await ctx.db.EXCUTE(sql1, [text[i]])
    // console.log(resultrequest1);
    if (resultrequest1[0].text == resultrequest[i].requestText) {
      let sql3 = 'update request set base64 =? where requestText=? '
      await ctx.db.EXCUTE(sql3, [resultrequest1[0].base64, resultrequest1[0].text])
      let sql4 = 'select * from request'
      result = await ctx.db.EXCUTE(sql4)
      // console.log(result);
    }
  }
  if (result) {
    message = { code: 200, msg: "成功", List: result }
  }
  else {
    message = { code: 400, mgs: '失败', List: result }
  }
  ctx.body = message
})
// 提交出租物品
router.post('/sale', async (ctx, next) => {
  let infoSale = JSON.parse(ctx.request.body)
  // console.log(infoSale.text);
  let message = {};
  let Depositprice = 30
  let timer = new Date;
  var hour = timer.getHours(); //获取当前小时
  var minute = timer.getMinutes(); //获取当前分钟
  var second = timer.getSeconds(); //获取当前秒
  let hours = hour < 10 ? "0" + hour : hour
  let minutes = minute < 10 ? "0" + minute : minute
  let seconds = second < 10 ? "0" + second : second
  let Date2 = hours + ":" + minutes + ":" + seconds
  // console.log(Date2);
  let sql = 'insert into sale (saleText,saleDate,avatarUrl,Depositprice,userName,shopprice,name) value (?, ?,?,?,?,?,?)'
  let result = await ctx.db.EXCUTE(sql, [infoSale.text, Date2, infoSale.avatar, Depositprice, infoSale.userName, infoSale.price, infoSale.name]);
  // console.log(result);
  if (result.length > 0) {
    message = { code: 200, msg: "成功" }
  }
  else {
    message = { code: 400, mgs: '失败' }
  }
  ctx.body = message
})

// 加入购物车
router.post('/addshop', async (ctx, next) => {
  let info = JSON.parse(ctx.request.body)
  console.log(info);
  let over = 0
  let shopState = 'shop';
  let ifDue = '未逾期'
  let message = {}
  let result4 = true
  // 购物车已经存在就不用再次加入
  let sql3 = "select shopText from shop where userName=?"
  let result3 = await ctx.db.EXCUTE(sql3, [info.shopName])
  // console.log(result3);
  // 通过前台传过来的userName在sale数据库中查找信息
  let sql = "select * from sale where saleId=?"
  let result = await ctx.db.EXCUTE(sql, [info.id])
  // console.log(result[0]);
  for (var i = 0; i < result3.length; i++) {
    if (result3[i].shopText == result[0].name) {
      result4 = false
    }
  }
  let sql1 = "select * from shop where shopText=? and userName=?"
  let result1 = await ctx.db.EXCUTE(sql1, [result[0].name, info.shopName])
  // console.log(result1);
  if (result1.length == 0 && result4) {
    let sql2 = 'insert into shop (shopName,userName,avatarUrl,shopImage,shopText,shopDeposit,shopPrice,overdueDeposit,shopState,ifDue) value(?,?,?,?,?,?,?,?,?,?)'
    let result2 = await ctx.db.EXCUTE(sql2, [info.shopName, info.userName, result[0].avatarUrl, result[0].base64, result[0].name, result[0].Depositprice, result[0].shopprice, over, shopState, ifDue])
    if (result2.affectedRows != 0) {
      message = { code: 200, mgs: "加入成功" }
    } else {
      message = { code: 401, mgs: "加入失败" }
    }
  }
  else {
    message = { code: 400, mgs: "已经加入购物车" }
  }
  ctx.body = message
})
//前端： 显示购物车列表
router.post('/shopList', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let { userName } = id;
  let sql = 'select * from shop where shopState = "noPay" and userName=?';
  let sql1 = 'select * from shop where shopState = "shop" and userName=?';
  console.log(userName);
  let res = await ctx.db.EXCUTE(sql, [userName])
  let res1 = await ctx.db.EXCUTE(sql1, [userName])
  res = [...res, ...res1]
  ctx.body = { List: res };
})
// 前端：购物车删除
router.post('/shopDelete', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let sql1 = 'delete from shop where shopId=?';
  let res1 = await ctx.db.EXCUTE(sql1, [id.shopId])
  if (res1.affectedRows != 0) {
    let sql2 = 'select * from shop'
    let res2 = await ctx.db.EXCUTE(sql2)
    ctx.body = { code: 200, List: res2 }
  }
  else {
    ctx.body = { code: 400 }
  }
})

// 显示出租信息
router.post('/fputsale', async (ctx, next) => {
  let text = [];
  let result = []
  let sql = 'select * from sale'
  // 查找照片的时候就要匹配上对应的text---已完成
  // 现在需要解决的就是怎么让sale库里的东西和img库里的照片匹配----已完成
  // 我往img中传入了text，我怎么把sql1查询后得到的结果插入到resulSale对象数组的每一个对象中
  let message = {}
  let resultSale = await ctx.db.EXCUTE(sql)
  for (var i = 0; i < resultSale.length; i++) {
    // console.log(resultSale.length);
    text[i] = resultSale[i].saleText
    // console.log(text[i]);
    // 查到全部信息后再和resultSale里的text对比，如果text相同就把imgUrl属性插入
    let sql1 = 'select * from saleimg where text=?'
    let resultSale1 = await ctx.db.EXCUTE(sql1, [text[i]])
    // console.log(resultSale1[0].text);
    if (resultSale1[0].text == resultSale[i].saleText) {
      let sql3 = 'update sale set base64 =? where saleText=? '
      await ctx.db.EXCUTE(sql3, [resultSale1[0].base64, resultSale1[0].text])
      let sql4 = 'select * from sale'
      result = await ctx.db.EXCUTE(sql4)
      // console.log(result);
    }
  }
  if (result) {
    message = { code: 200, msg: "成功", List: result }
  }
  else {
    message = { code: 400, mgs: '失败', List: result }
  }
  ctx.body = message
})
// 接受存储评论（包括评论内容，以及用户信息和被评论作者信息）
router.post('/pinglun', async (ctx, next) => {
  let info = JSON.parse(ctx.request.body)
  // console.log(info);
  let timer = new Date;
  var hour = timer.getHours(); //获取当前小时
  var minute = timer.getMinutes(); //获取当前分钟
  var second = timer.getSeconds(); //获取当前秒
  let hours = hour < 10 ? "0" + hour : hour
  let minutes = minute < 10 ? "0" + minute : minute
  let seconds = second < 10 ? "0" + second : second
  let Date2 = hours + ":" + minutes + ":" + seconds
  console.log(Date2);
  // 如果评论内容为空就不存储
  if (info.text) {
    let sql = 'insert into pinglun (userName, pinglunName,pinglunDate,pinglun) value (?,?,?,?)'
    await ctx.db.EXCUTE(sql, [info.userName, info.pinglunName, Date2, info.text]);
  }
  let sql1 = 'select * from pinglun where userName=?'
  let pinglunList = await ctx.db.EXCUTE(sql1, [info.userName])
  // console.log(pinglunList);
  ctx.body = { List: pinglunList };
})
// 显示评论
router.post('/fputpinglun', async (ctx, next) => {
  let info = JSON.parse(ctx.request.body)
  let sql1 = 'select * from pinglun where userName=?and pinglunName=?'
  let pinglunList = await ctx.db.EXCUTE(sql1, [info.userName, info.pinglunName])
  // console.log(pinglunList);
  ctx.body = { List: pinglunList };
})
// 与卖家聊天向数据库插入聊天人信息
router.post('/fchat', async (ctx, next) => {
  let info = JSON.parse(ctx.request.body)
  // console.log(info);
  let message = {}
  if (info.userName != info.AuserName) {
    let sql1 = 'select * from chat where userName=? and AuserName=?'
    let userList = await ctx.db.EXCUTE(sql1, [info.userName, info.AuserName])
    // console.log(userList);
    if (userList.length == 0) {
      let sql2 = 'select avatarUrl from users where userName=?'
      let result = await ctx.db.EXCUTE(sql2, [info.AuserName])
      // console.log(result);
      let sql = 'insert into chat (userName, AuserName,Auseravatar) value (?,?,?)'
      let result1 = await ctx.db.EXCUTE(sql, [info.userName, info.AuserName, result[0].avatarUrl])
      // console.log(result1);
      message = { code: 200, List: result1 };
    }
    else {
      let sql3 = 'select * from chat'
      let result2 = await ctx.db.EXCUTE(sql3)
      message = { code: 401, List: result2 }
    }
  }
  else {
    message = { code: 400 }
  }
  ctx.body = message;
})
// 搜索
router.post('/search', async (ctx, next) => {
  let info = JSON.parse(ctx.request.body)
  console.log(info);
  let List = []
  let message = {}
  if (info.isClick) {
    let sql = 'select * from sale where saleText like ?'
    let List2 = await ctx.db.EXCUTE(sql, ["%" + info.text + "%"])
    message = { code: info.isClick, List: List2 }
  }
  else {
    let sql1 = 'select * from request where requestText like ?'
    let List1 = await ctx.db.EXCUTE(sql1, ["%" + info.text + "%"])
    message = { code: info.isClick, List: List1 }
  }
  ctx.body = message;
})
// 需求上传图片
router.post('/uploadimg', async (ctx, next) => {
  let info = JSON.parse(ctx.request.body)
  let size = info.height * info.width
  let message = {}
  // console.log(info);
  let sql = "insert into img (imgUrl,size,userName,text,base64)values(?,?,?,?,?)"
  let result = await ctx.db.EXCUTE(sql, [info.url, size, info.userName, info.text, info.base64]);
  if (result.affectedRows != 0) {
    message = { code: 200 }
  }
  else {
    message = { code: 400 }
  }
  ctx.body = message
  // ctx.body='img'
})
const uploadImg = (ctx) => {
  // 图片上传配置信息(可扩展，下载地址，允许上传多张照片)
  const form = formidable({
    multiples: true,
    uploadDir: dirPath,
    keepExtensions: true,
    allowEmptyFiles: false
  });
  // 数据库上传图片操作
  return new Promise((resolve, reject) => {
    form.parse(ctx.req, (err, fields, files) => {
      if (err) {
        reject(err);
        return;
      }
      else {
        resolve({ ok: true, fields, files });
      }
    });
  });
}
// 上传图片
router.post('/backuploadimg', async (ctx, next) => {
  let managerId=ctx.request.url.split('?')[1].split('=')[1];
  // console.log(ctx.request.url);
  let message={}
  let flag = await uploadImg(ctx);
  if(flag.ok){
    let name=flag.files.file.originalFilename
    console.log(flag.files.file);
    let sql = "update manager set imgname=? where managerId=?"
    let result = await ctx.db.EXCUTE(sql, [name,managerId]);
    // console.log(result);
    if(result.affectedRows!=0){
      message={code:200}
    }
    else{
      message={code:400}
    }
  }
  ctx.body=message
})

router.get('/getimage/:name', async (ctx, next) => {
  console.log(ctx.params.name);
  let imgpath = path.join(dirPath, ctx.params.name)
  let imgconent = fs.readFileSync(imgpath);
  ctx.body = imgconent;
})
// 支付成功后扣除支付方商品单价＋押金，收款方余额加入单价*0.（平台盈利单价的20%）
router.post('/changeMoney', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let sql1 = 'select * from shop where shopId=? ';
  let res1 = await ctx.db.EXCUTE(sql1, [id.shopId])
  if (res1.length > 0) {
    // 扣除支付方商品单价＋押金
    let sql2 = 'select * from package where userName=?';
    let res2 = await ctx.db.EXCUTE(sql2, [id.userName])
    if (res2.length == 0) {
      message = { code: 401 }
    }
    else {
      let sql3 = 'update package set money=? where userName=?';
      let res3 = await ctx.db.EXCUTE(sql3, [res2[0].money - 30 - res1[0].shopPrice, id.userName])
      // 收款方余额增加单价*0.8
      let sql4 = 'select * from package where userName=? ';
      let res4 = await ctx.db.EXCUTE(sql4, [id.shopName])
      if (res4 == 0) {
        let sql6 = 'insert into package (userName) values (?) '
        let result6 = await ctx.db.EXCUTE(sql6, [shopName])
        if (result6.affectedRows != 0) {
          let sql5 = 'update package set money=? where userName=?';
          let res5 = await ctx.db.EXCUTE(sql5, [res4[0].money + res1[0].shopPrice * 0.8, id.shopName])
          ctx.body = { code: 200 }
        }
      }
      else {
        let sql5 = 'update package set money=? where userName=?';
        let res5 = await ctx.db.EXCUTE(sql5, [res4[0].money + res1[0].shopPrice * 0.8, id.shopName])
        ctx.body = { code: 200 }
      }

    }
  }
  else {
    message = { code: 400 }

  }
})
// 前端：显现余额
router.post('/Package', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body)
  let sql = 'select * from package where userName=?'
  let List = await ctx.db.EXCUTE(sql, [id.userName]);
  console.log(List)
  ctx.body = { List: List };
})
// 前端：修改用户余额
router.post('/chongzhi', async (ctx, next) => {
  let message = {};
  let user = JSON.parse(ctx.request.body)
  let { userName, money1 } = user
  console.log(userName, money1);
  let sql1 = 'select * from package where userName = ?'
  let result1 = await ctx.db.EXCUTE(sql1, [userName])
  // console.log(result1[0].money);
  if (result1.length == 0) {
    let sql4 = 'insert into package (userName) values (?) '
    let result4 = await ctx.db.EXCUTE(sql4, [userName])
    if (result4.affectedRows != 0) {
      let sql5 = 'update package set money=? where userName=?'
      let result5 = await ctx.db.EXCUTE(sql5, [money1 * 1.0, userName])
      let sql6 = 'select * from package where userName = ?'
      let result6 = await ctx.db.EXCUTE(sql6, userName)
      // console.log(result3[0].money);
      message = { code: 200, List: result6 }
    }
  }
  else {
    let sql2 = 'update package set money=? where userName=?'
    let results = await ctx.db.EXCUTE(sql2, [money1 * 1.0 + result1[0].money * 1.0, userName])
    let sql3 = 'select * from package where userName = ?'
    let result3 = await ctx.db.EXCUTE(sql3, userName)
    console.log(result3[0].money);
    message = { code: 200, List: result3 }
    // console.log(results)
  }
  ctx.body = message;
})
//前端：退还押金
router.post('/qiandelCash', async (ctx, next) => {
  let message = {};
  let id = JSON.parse(ctx.request.body);
  let sql = 'select * from shop where shopId = ?'
  let result = await ctx.db.EXCUTE(sql, [id.shopId])
  console.log(result[0].userName);
  let sql3 = 'select * from package where userName = ?'
  let result3 = await ctx.db.EXCUTE(sql3, [result[0].userName])
  console.log(result3[0].money);
  if (result3.length == 0) {
    ctx.body = { code: 400 }
  }
  else {
    let sql2 = 'update package set money=? where userName=?'
    let results = await ctx.db.EXCUTE(sql2, [result3[0].money * 1.0 + 15, result[0].userName])
    let sql4 = 'select * from package where userName = ?'
    let result4 = await ctx.db.EXCUTE(sql4, result[0].userName)
    console.log(result4[0].money);
    ctx.body = { code: 200, List: result3 }
    console.log(results)
    let sql1 = 'update shop set shopState="end" where shopId=?';
    let res1 = await ctx.db.EXCUTE(sql1, [id.shopId])
    console.log(res1);
    if (res1.affectedRows != 0) {
      let sql2 = 'select * from shop where userName=?'
      let res2 = await ctx.db.EXCUTE(sql2, [result[0].userName])
      ctx.body = { code: 200, List: res2 }
    } else {
      ctx.body = { code: 400 }
    }
  };
})
// 需求上传图片
router.post('/saleuploadimg', async (ctx, next) => {
  let info = JSON.parse(ctx.request.body)
  let size = info.height * info.width
  let message = {}
  // console.log(info);
  let sql = "insert into saleimg (imgUrl,size,userName,text,base64)values(?,?,?,?,?)"
  let result = await ctx.db.EXCUTE(sql, [info.url, size, info.userName, info.text, info.base64]);
  if (result.affectedRows != 0) {
    message = { code: 200 }
  }
  else {
    message = { code: 400 }
  }
  ctx.body = message
  // ctx.body='img'
})
// 提交头像
router.post('/editavatar', async (ctx, next) => {
  let info = JSON.parse(ctx.request.body)
  let message = {}
  // console.log(info);
  let sql = "insert into avatar (avatarUrl,userName,base64)values(?,?,?)"
  let result = await ctx.db.EXCUTE(sql, [info.url, info.text, info.base64]);
  if (result.affectedRows != 0) {
    message = { code: 200 }
  }
  else {
    message = { code: 400 }
  }
  ctx.body = message
  // ctx.body='img'
})
//前端：删除地址
router.post('/qiandelAddress', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let sql1 = 'delete from address where addressId=?';
  let res1 = await ctx.db.EXCUTE(sql1, [id.addressId])
  console.log(id.addressId);
  if (res1.affectedRows != 0) {
    let sql2 = 'select * from address'
    let res2 = await ctx.db.EXCUTE(sql2)
    ctx.body = { code: 200, List: res2 }
  } else {
    ctx.body = { code: 400 }
  }
})
// 前端：显现所有合同信息
router.post('/Contract', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let sql = 'select * from contract where AuserName=?'
  let List = await ctx.db.EXCUTE(sql, [id.userName]);
  let sql1 = 'select * from contract where BuserName=?'
  let List1 = await ctx.db.EXCUTE(sql1, [id.userName]);
  List = [...List, ...List1]
  console.log(List)
  ctx.body = { List: List };
})

// 前端：显现所有退还押金信息
router.post('/DepositRefund', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let sql = 'select * from shop where shopName=? and shopState="pay"'
  let List = await ctx.db.EXCUTE(sql, [id.userName]);
  console.log(List)
  ctx.body = { List: List };
})



// 前端：显现所有需求列表
router.post('/puMyrequest', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body)
  let sql = 'select * from request where userName=?'
  let List = await ctx.db.EXCUTE(sql, [id.userName]);
  console.log(List)
  ctx.body = { List: List };
})
// 前端：显现所有出租物品
router.post('/puMysale', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body)
  let sql = 'select * from sale where userName=?'
  let List = await ctx.db.EXCUTE(sql, [id.userName]);
  console.log(List)
  ctx.body = { List: List };
})

// 前端：显现所有聊天
router.post('/chat', async (ctx, next) => {
  let user = JSON.parse(ctx.request.body)
  let { userName1, AuserName, userName } = user
  console.log(userName1);
  let sql1 = 'select * from chat where userName = ?'
  let result1 = await ctx.db.EXCUTE(sql1, [userName1])
  ctx.body = { List: result1 };
})

// 前端：增加对话
router.post('/addlist', async (ctx, next) => {
  let list = ctx.request.body
  let { AuserName, BuserName, name, message } = JSON.parse(list)
  let sql = 'insert into userChat (AuserName,BuserName,name,message) value (?,?,?,?)'
  console.log(list);
  console.log(AuserName, BuserName, name, message);
  await ctx.db.EXCUTE(sql, [AuserName, BuserName, name, message])
  message = { code: 200 }
  ctx.body = message;
})

// 与卖家聊天向数据库插入聊天人信息
router.post('/fchat', async (ctx, next) => {
  let info = JSON.parse(ctx.request.body)
  let message = {}
  let sql1 = 'select * from chat where userName=?and AuserName=?'
  let userList = await ctx.db.EXCUTE(sql1, [info.userName, info.AuserName])
  // console.log(userList);
  if (userList == []) {
    let sql = 'insert into chat (userName, AuserName) value (?,?)'
    await ctx.db.EXCUTE(sql, [info.userName, info.AuserName])
    message = { code: 200 };
  }
  else {
    message = { code: 400 }
  }
  ctx.body = message;
})

// 前端：显示对话
router.post('/list', async (ctx, next) => {
  let user = JSON.parse(ctx.request.body)
  let { AuserName, BuserName } = user
  console.log(AuserName, BuserName);
  let sql1 = 'select * from userChat where AuserName = ? and BuserName=?'
  let result1 = await ctx.db.EXCUTE(sql1, [AuserName, BuserName])
  let sql2 = 'select * from userChat where AuserName = ? and BuserName=?'
  let result2 = await ctx.db.EXCUTE(sql2, [BuserName, AuserName])
  result1 = [...result1, ...result2]
  ctx.body = { List: result1 };
})

// 前端：修改地址信息
router.post('/befoChangeAddress', async (ctx, next) => {
  let message = {};
  let user = JSON.parse(ctx.request.body)
  let { userName1, addressName, phoneNum, park, building, addressId } = user
  console.log(userName1);
  let sql1 = 'select addressId from address where userName = ?'
  let sql2 = 'update address set addressName=?, phoneNum=?,park=?,building=? where addressId=?'
  let result1 = await ctx.db.EXCUTE(sql1, [userName1])
  console.log(result1[0].addressId);
  if (result1.length == 0) {
    message = { code: 400 }
  }
  else {
    let results = await ctx.db.EXCUTE(sql2, [addressName, phoneNum, park, building, result1[0].addressId])
    let sql3 = 'select * from users where userId = ?'
    let result3 = await ctx.db.EXCUTE(sql3, [result1[0].addressId])
    message = { code: 200, List: result3 }
    console.log(results)
  }
  ctx.body = message;
})
// 前端：显现所有地址信息
router.post('/DeliveryAddress', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let sql = 'select * from address where userName=?'
  let List = await ctx.db.EXCUTE(sql, [id.userName]);
  console.log(List)
  ctx.body = { List: List };
})
//支付界面获取对应收货地址信息
router.post('/addressList', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let sql = 'select * from address where addressId=?';
  let res = await ctx.db.EXCUTE(sql, [id.addressId])
  if (res.length > 0) {
    ctx.body = { code: 200, List: res }
  }
  else {
    ctx.body = { code: 400, message: 'fail' }
  }
})

//支付界面获取对应商品信息
router.post('/payList', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let { shopId } = id
  let sql = 'select * from shop where shopId=?';
  let res = await ctx.db.EXCUTE(sql, [shopId])
  if (res.length > 0) {
    ctx.body = { code: 200, List: res }
  }
  else {
    ctx.body = { code: 400, message: 'fail' }
  }
})

//取消支付后将商品状态修改为“noPay”
router.post('/cancelPay', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let { shopId } = id
  console.log(id);
  let sql1 = 'select * from shop where shopId=? and shopState=?';
  let res1 = await ctx.db.EXCUTE(sql1, [id.shopId, id.shopState])
  if (res1.length > 0) {
    let sql2 = 'update shop set shopState=? where shopId=?';
    let res2 = await ctx.db.EXCUTE(sql2, ["noPay", shopId])
    ctx.body = { code: 200 }
  }
  else {
    ctx.body = { code: 400 }
  }
})

//支付成功后将商品状态修改为"pay"
router.post('/onPay', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let { shopId, shopState } = id
  let sql1 = 'select * from shop where shopId=? and shopState=?';
  let res1 = await ctx.db.EXCUTE(sql1, [id.shopId, id.shopState])
  if (res1.length > 0) {
    let sql2 = 'update shop set shopState=? where shopId=?';
    let res2 = await ctx.db.EXCUTE(sql2, ["pay", shopId])
    ctx.body = { code: 200 }
  }
  else {
    ctx.body = { code: 400 }
  }
})

// 订单中点击“全部” “待付款” “已支付”"已出租”“已完成”出现对应内容
router.post('/order', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let { userName } = id
  if (id.shopState == "全部") {
    let sql = 'select * from shop where shopState = "noPay" and userName=?';
    let res = await ctx.db.EXCUTE(sql, [userName])
    let sql1 = 'select * from shop where shopState = "pay" and userName=?';
    let res1 = await ctx.db.EXCUTE(sql1, [userName])
    let sql2 = 'select * from shop where shopState = "end" and userName=?';
    let res2 = await ctx.db.EXCUTE(sql2, [userName])
    res = [...res, ...res1,...res2]
    let Asql1 = 'select * from shop where shopState = "pay" and shopName=?';
    let Ares1 = await ctx.db.EXCUTE(Asql1, [userName])
    res = [...res, ...Ares1]
    ctx.body = { List: res };
  } 
  else if (id.shopState == "待付款") {
    let sql = 'select * from shop where shopState = "noPay" and userName=?';
    let res = await ctx.db.EXCUTE(sql, [userName])
    console.log(res);
    ctx.body = { List: res };
  } 
  else if (id.shopState == "已支付") {
    let sql = 'select * from shop where shopState = "pay" and userName=?';
    let res = await ctx.db.EXCUTE(sql, [userName])
    console.log(res);
    ctx.body = { List: res };
  } 
  else if (id.shopState == "已完成") {
    let sql = 'select * from shop where shopState = "end" and userName=?';
    let res = await ctx.db.EXCUTE(sql, [userName])
    console.log(res);
    ctx.body = { List: res };
  } 
  else {
    let sql = 'select * from shop where shopState = "pay" and shopName=?';
    let res = await ctx.db.EXCUTE(sql, [userName])
    console.log(res);
    ctx.body = { List: res };
  }

})

//支付成功后将逾期押金修改为15
router.post('/over', async (ctx, next) => {
  let id = JSON.parse(ctx.request.body);
  let sql1 = 'select * from shop where shopId=?';
  let res1 = await ctx.db.EXCUTE(sql1, [id.shopId])
  console.log(res1);
  if (res1.length > 0) {
    let sql2 = 'update shop set  ifDue="逾期" where shopId=?';
    let res2 = await ctx.db.EXCUTE(sql2, [id.shopId])
    let sql3 = 'update shop set  overdueDeposit="15" where shopId=?';
    let res3 = await ctx.db.EXCUTE(sql3, [id.shopId])
    console.log("aaaaaaaaaaaaaaa");
    console.log(res2);
    ctx.body = { code: 200 }
  }
  else {
    ctx.body = { code: 400 }
  }
})

// 前端：增加地址信息
router.post('/befoAddAddress', async (ctx, next) => {
  let address = JSON.parse(ctx.request.body)
  // let { userName, addressName, phoneNum, park, building } = JSON.parse(address)
  let sql1 = 'select * from users where userName=?'
  let sql = 'insert into address (userName, addressName,phoneNum,park,building) value (?,?,?,?,?)'
  let result1 = await ctx.db.EXCUTE(sql1, [address.userName1])
  console.log(result1);
  if (result1.length == 0) {
    message = { code: 400 }
  }
  else {
    // console.log(userName, addressName, phoneNum, park, building);
    await ctx.db.EXCUTE(sql, [address.userName1, address.addressName, address.phoneNum, address.park, address.building])
    message = { code: 200 }
  }
  ctx.body = message;
})

// 前端：修改用户信息
router.post('/Etiduser', async (ctx, next) => {
  let message = {};
  let user = JSON.parse(ctx.request.body)
  // let { userName1, userName, password, sex, birthday } = JSON.parse(user)
  console.log(user);
  let sql1 = 'select userId from users where userName=?'
  let sql2 = 'update users set userName=?, password=?,sex=?,birthday=? where userId=?'
  let result1 = await ctx.db.EXCUTE(sql1, [user.userName1])
  console.log(result1[0].userId);
  if (result1.length == 0) {
    message = { code: 400 }
  }
  else {
    let results = await ctx.db.EXCUTE(sql2, [user.userName, user.password, user.sex, user.birthday, result1[0].userId])
    if (results.affectedRows != 0) {
      let sql3 = 'select userId from users where userName=?'
      let result3 = await ctx.db.EXCUTE(sql3, [user.userName])
      let sql4 = 'select base64 from avatar where userName=?'
      let result4 = await ctx.db.EXCUTE(sql4, [user.userName])
      console.log(result4, result3);
      let sql5 = 'update users set avatarUrl=? where userId=?'
      let result5 = await ctx.db.EXCUTE(sql5, [result4[0].base64, result3[0].userId])
      // console.log(result5);
      if (result5.affectedRows != 0) {
        let sql6 = 'select * from users where userName=?'
        let result6 = await ctx.db.EXCUTE(sql6, [user.userName])
        console.log(result6);
        message = { code: 200, List: result6 }
      }
      else {
        message = { code: 401 }
      }
    }
  }
  ctx.body = message;
})
// 在个人中心展示头像
router.post("/putavatar", async (ctx, next) => {
  // console.log(ctx.request.body);
  let info = JSON.parse(ctx.request.body)
  console.log(info);
  let sql = 'select * from users where userName=?';
  let res = await ctx.db.EXCUTE(sql, [info.userName]);
  // console.log(res);
  if (res.length > 0) {
    ctx.body = { code: 200, message: 'success', List: res }
  } else {
    ctx.body = { code: 400, message: "fail" }
  }
})
// 登录
router.post("/forwordlogin", async (ctx, next) => {
  console.log(ctx.request.body);
  let sql = 'select * from users where userName=? and password=?';
  let res = await ctx.db.EXCUTE(sql, [ctx.request.body.userName, ctx.request.body.password]);
  if (res.length > 0) {
    ctx.body = { code: 200, message: res }
  } else {
    ctx.body = { code: 400, message: "fail" }
  }
})
//查看输入用户名是否已注册
router.post("/selectUser", async (ctx, next) => {
  let sql1 = 'select * from users where userName=? ';
  let res1 = await ctx.db.EXCUTE(sql1, [ctx.request.body.userName]);
  if (res1.length > 0) {
    ctx.body = { code: 200, message: "该用户名已存在" }
  } else{
    ctx.body = { code: 300, message: "该用户名未存在" }
  }
})
//输入用户名未被注册后，弹框协议进行注册
router.post("/forwordregister", async (ctx, next) => {
    let sql = 'insert into users(userName,password) values (?,?)';
    let res = await ctx.db.EXCUTE(sql, [ctx.request.body.userName, ctx.request.body.password]); 
  if (res) {
    ctx.body = { code: 200, message: "success" }
  }
  else {
    ctx.body = { code: 300, message: "fail" }
  }
})

// 前端：忘记密码
router.post("/forget", async (ctx, next) => {
  console.log(ctx.request.body);
  let sql = 'select password from users where userName=? and birthday=?';
  let res = await ctx.db.EXCUTE(sql, [ctx.request.body.userName, ctx.request.body.birthday]);
  if (res.length > 0) {
    console.log(res);
    console.log(res.password);
    ctx.body = { code: 200, message: res }
  } else {
    ctx.body = { code: 400, message: "fail" }
  }
})
// 前端：显现所有地址信息
router.post('/DeliveryAddress', async (ctx, next) => {
  let sql = 'select * from address'
  let pinglunList = await ctx.db.EXCUTE(sql);
  console.log(pinglunList)
  ctx.body = { List: pinglunList };
})

// 前端：增加地址信息
router.post('/befoAddAddress', async (ctx, next) => {
  let address = ctx.request.body
  let { userName1, addressName, phoneNum, park, building } = JSON.parse(address)
  let sql1 = 'select * from address where userName=? '
  let sql = 'insert into address (userName, addressName,phoneNum,park,building) value (?,?,?,?,?)'
  let result1 = await ctx.db.EXCUTE(sql1, [userName1])
  console.log(result1);
  if (result1.length == 0) {
    message = { code: 400 }
  }
  else {
    console.log(userName1, addressName, phoneNum, park, building);
    await ctx.db.EXCUTE(sql, [userName1, addressName, phoneNum, park, building])
    message = { code: 200 }
  }
  ctx.body = message;
})

// 后台登录
router.post("/login", async (ctx, next) => {
  let user = ctx.request.body
  let { managerName, password } = user;
  console.log(user);
  let message = {}
  let sql = 'select * from manager where managerName=? and password=?'
  let result =await ctx.db.EXCUTE(sql, [managerName, password]);
  console.log(result);
  if (result.length == 0) {
    message = { code: 400 }
  } else {
    console.log(result[0].managerName);
    const token = jwt.sign({
      managerName: result[0].managerName,
      password: result[0].password,
      
    }, mykey)
    message = { code: 200, token: token, success: true,List:{managerId: result[0].managerId,imgname: result[0].imgname,managerName: result[0].managerName,} }
  }
  ctx.body = message;
})

// 后台注册
router.post('/register', async (ctx, next) => {
  let user = ctx.request.body
  // console.log(user);
  let sql1 = 'select * from manager where managerName = ?'
  let sql2 = 'insert into manager (managerName, password) value (?, ?)'
  let result = await ctx.db.EXCUTE(sql1, [user.managerName])
  console.log(result);
  if (result.length > 0) {
    message = { code: 400 }
  }
  else {
    await ctx.db.EXCUTE(sql2, [user.managerName, user.password])
    message = { code: 200 }
  }
  ctx.body = message;
})

// 后台：查询显示用户信息
router.post('/putuser', async (ctx, next) => {
  let sql = 'select * from users'
  let usersList = await ctx.db.EXCUTE(sql);
  ctx.body = { List: usersList };
})

// 后台：增加用户信息
router.post('/adduser', async (ctx, next) => {
  let user = ctx.request.body
  let { userName, password, sex, birthday, avatarUrl } = user
  console.log(user);
  let sql1 = 'select * from users where userName = ?'
  let sql2 = 'insert into users (userName, password, sex, birthday,avatarUrl) value (?,?,?,?,?)'
  let result = await ctx.db.EXCUTE(sql1, [userName])
  console.log(result);
  if (result.length > 0) {
    message = { code: 400 }
  }
  else {
    await ctx.db.EXCUTE(sql2, [userName, password, sex, birthday, avatarUrl])
    message = { code: 200 }
  }
  ctx.body = message;
})

// 后台：删除用户信息
router.post('/deluser', async (ctx, next) => {
  let user = ctx.request.body
  console.log(user);
  let { userName } = user;
  let message = {}
  let sql1 = 'select * from users where userName=?'
  let sql = 'delete  from users where userName=?'
  let result = await ctx.db.EXCUTE(sql1, [userName])
  console.log(result);
  if (result.length == 0) {
    message = { code: 401 }
  } else {
    await ctx.db.EXCUTE(sql, [userName], async (err, data) => {
      console.log(data);
      if (err) {
        message = { code: 400 }
      }
      if (data.affectedRows > 0) {
        message = { code: 200 }
      }
      else { message = { code: 202 } }
    })
  }
  ctx.body = message
})

// 后台：修改用户信息
router.post('/edituser', async (ctx, next) => {
  let user = ctx.request.body
  let { userId, userName, password, sex, birthday, avatarUrl } = user
  console.log(user);
  let sql1 = 'select * from users where userId = ?'
  let sql2 = 'update users set userName=?, password=?,sex=?,birthday=?,avatarUrl=? where userId=?'
  let result = await ctx.db.EXCUTE(sql1, [userId])
  console.log(result);
  if (result.length == 0) {
    message = { code: 400 }
  }
  else {
    let results = await ctx.db.EXCUTE(sql2, [userName, password, sex, birthday, avatarUrl, userId])
    message = { code: 200, List: results }
    console.log(results)
  }
  ctx.body = message;
})

// 后台：查询准确用户信息
router.post('/seluser', async (ctx, next) => {
  let user = ctx.request.body
  let { userName, password, sex, birthday, avatarUrl } = user
  console.log(user);
  let sql = 'select * from users where userName = ?'
  let result = await ctx.db.EXCUTE(sql, [userName, password, sex, birthday, avatarUrl])
  console.log(result);
  if (result.length == 0) {
    message = { code: 400 }
  }
  else {
    message = { code: 200, List: result }
  }
  ctx.body = message;
})

// 后台：获取用户分页
router.get('/getUserData', async (ctx, res) => {
  let sql = 'select * from users'
  let saleList = await ctx.db.EXCUTE(sql);
  ctx.body = { List: saleList };
})

// 后台：用户分页查询
router.post('/pageuser', async (ctx, res) => {
  let user = ctx.request.body;
  // console.log(user);
  let message = {};
  let pageNo = user.page || 1;
  let pageCount = user.pageSize || 10;
  let pageSize = pageCount;
  let page = (pageNo - 1) * pageCount;
  console.log(page, pageSize);
  let sql = `select * from users limit ${page},${pageSize}`;
  let results = await ctx.db.EXCUTE(sql)
  if (results == 0) {
    message = { code: 400, message: "获取分页数据失败" };
  } else {
    // console.log(results);
    message = { code: 200, message: '获取分页数据成功', List: results }
  }
  ctx.body = message
})

// 后台：获取需求列表分页
router.get('/getRequestData', async (ctx, res) => {
  let sql = 'select * from request'
  let saleList = await ctx.db.EXCUTE(sql);
  ctx.body = { List: saleList };
})

// 后台：需求列表分页查询
router.post('/pageRequest', async (ctx, res) => {
  let user = ctx.request.body;
  // console.log(user);
  let message = {};
  let pageNo = user.page || 1;
  let pageCount = user.pageSize || 10;
  let pageSize = pageCount;
  let page = (pageNo - 1) * pageCount;
  console.log(page, pageSize);
  let sql = `select * from request limit ${page},${pageSize}`;
  let results = await ctx.db.EXCUTE(sql)
  if (results == 0) {
    message = { code: 400, message: "获取分页数据失败" };
  } else {
    // console.log(results);
    message = { code: 200, message: '获取分页数据成功', List: results }
  }
  ctx.body = message
})

// 后台：查询显示需求列表信息
router.post('/putRequest', async (ctx, next) => {
  let sql = 'select * from request'
  let requestList = await ctx.db.EXCUTE(sql);
  ctx.body = { List: requestList };
})

// 后台：增加需求列表信息
router.post('/addRequest', async (ctx, next) => {
  let request = ctx.request.body
  let { requestId, avatarUrl, userName, requestDate, requestText, requestImage } = request
  console.log(request);
  let sql1 = 'select * from request where requestId = ?'
  let sql2 = 'insert into request (requestId,avatarUrl,userName,requestDate,requestText,requestImage) value (?,?,?,?,?,?)'
  let result = await ctx.db.EXCUTE(sql1, [requestId])
  console.log(result);
  if (result.length > 0) {
    message = { code: 400 }
  }
  else {
    await ctx.db.EXCUTE(sql2, [requestId, avatarUrl, userName, requestDate, requestText, requestImage])
    message = { code: 200 }
  }
  ctx.body = message;
})

// 后台：删除需求列表信息
router.post('/delRequest', async (ctx, next) => {
  let request = ctx.request.body
  console.log(request);
  let { requestId } = request;
  let message = {}
  let sql1 = 'select * from request where requestId=?'
  let sql = 'delete from request where requestId=?'
  let result = await ctx.db.EXCUTE(sql1, [requestId])
  console.log(result);
  if (result.length == 0) {
    message = { code: 401 }
  } else {
    await ctx.db.EXCUTE(sql, [requestId], async (err, data) => {
      console.log(data);
      if (err) {
        message = { code: 400 }
      }
      if (data.affectedRows > 0) {
        message = { code: 200 }
      }
      else { message = { code: 202 } }
    })
  }
  ctx.body = message
})

// 后台：修改需求列表信息
router.post('/editRequest', async (ctx, next) => {
  let request = ctx.request.body
  let { requestId, avatarUrl, userName, requestDate, requestText, requestImage } = request
  console.log(request);
  let sql1 = 'select * from request where requestId = ?'
  let sql2 = 'update request set userName=?, avatarUrl=?,requestDate=?,requestText=?,requestImage=? where requestId=?'
  let result = await ctx.db.EXCUTE(sql1, [requestId])
  console.log(result);
  if (result.length == 0) {
    message = { code: 400 }
  }
  else {
    let results = await ctx.db.EXCUTE(sql2, [userName, avatarUrl, requestDate, requestText, requestImage, requestId])
    message = { code: 200, List: results }
    console.log(results)
  }
  ctx.body = message;
})

// 后台：查询准确需求列表信息
router.post('/selRequest', async (ctx, next) => {
  let request = ctx.request.body
  let { userName } = request
  console.log(request);
  let sql = 'select * from request where userName = ?'
  let result = await ctx.db.EXCUTE(sql, [userName])
  console.log(result);
  if (result.length == 0) {
    message = { code: 400 }
  }
  else {
    message = { code: 200, List: result }
  }
  ctx.body = message;
})

// 后台：获取出租物品分页
router.post('/getSaleData', async (ctx, res) => {
  let sql = 'select * from sale'
  let saleList = await ctx.db.EXCUTE(sql);
  ctx.body = { List: saleList };
})

// 后台：出租物品分页查询
router.post('/pageSale', async (ctx, res) => {
  let user = ctx.request.body;
  // console.log(user);
  let message = {};
  let pageNo = user.page || 1;
  let pageCount = user.pageSize || 10;
  let pageSize = pageCount;
  let page = (pageNo - 1) * pageCount;
  console.log(page, pageSize);
  let sql = `select * from sale limit ${page},${pageSize}`;
  let results = await ctx.db.EXCUTE(sql)
  if (results == 0) {
    message = { code: 400, message: "获取分页数据失败" };
  } else {
    // console.log(results);
    message = { code: 200, message: '获取分页数据成功', List: results }
  }
  ctx.body = message
})

// 后台：查询显示出租物品信息
router.post('/putSale', async (ctx, next) => {
  let sql = 'select * from sale'
  let saleList = await ctx.db.EXCUTE(sql);
  ctx.body = { List: saleList };
})

// 后台：增加出租物品信息
router.post('/addSale', async (ctx, next) => {
  let sale = ctx.request.body
  let { saleId, avatarUrl, userName, saleDate, saleText, saleImage } = sale
  console.log(sale);
  let sql1 = 'select * from sale where saleId = ?'
  let sql2 = 'insert into sale (saleId,avatarUrl,userName,saleDate,saleText,saleImage) value (?,?,?,?,?,?)'
  let result = await ctx.db.EXCUTE(sql1, [saleId])
  console.log(result);
  if (result.length > 0) {
    message = { code: 400 }
  }
  else {
    await ctx.db.EXCUTE(sql2, [saleId, avatarUrl, userName, saleDate, saleText, saleImage])
    message = { code: 200 }
  }
  ctx.body = message;
})

// 后台：删除出租物品信息
router.post('/delSale', async (ctx, next) => {
  let sale = ctx.request.body
  console.log(sale);
  let { saleId } = sale;
  let message = {}
  let sql1 = 'select * from sale where saleId=?'
  let sql = 'delete from sale where saleId=?'
  let result = await ctx.db.EXCUTE(sql1, [saleId])
  console.log(result);
  if (result.length == 0) {
    message = { code: 401 }
  } else {
    await ctx.db.EXCUTE(sql, [saleId], async (err, data) => {
      console.log(data);
      if (err) {
        message = { code: 400 }
      }
      if (data.affectedRows > 0) {
        message = { code: 200 }
      }
      else { message = { code: 202 } }
    })
  }
  ctx.body = message
})

// 后台：修改出租物品信息
router.post('/editSale', async (ctx, next) => {
  let sale = ctx.request.body
  let { saleId, avatarUrl, userName, saleDate, saleText, saleImage } = sale
  console.log(sale);
  let sql1 = 'select * from sale where saleId = ?'
  let sql2 = 'update sale set userName=?, avatarUrl=?,saleDate=?,saleText=?,saleImage=? where saleId=?'
  let result = await ctx.db.EXCUTE(sql1, [saleId])
  console.log(result);
  if (result.length == 0) {
    message = { code: 400 }
  }
  else {
    let results = await ctx.db.EXCUTE(sql2, [saleId, avatarUrl, userName, saleDate, saleText, saleImage])
    message = { code: 200, List: results }
    console.log(results)
  }
  ctx.body = message;
})

// 后台：查询准确出租物品信息
router.post('/selSale', async (ctx, next) => {
  let sale = ctx.request.body
  let { userName } = sale
  console.log(sale);
  let sql = 'select * from sale where userName = ?'
  let result = await ctx.db.EXCUTE(sql, [userName])
  console.log(result);
  if (result.length == 0) {
    message = { code: 400 }
  }
  else {
    message = { code: 200, List: result }
  }
  ctx.body = message;
})

// 后台：获取地址信息分页
router.get('/getAddressData', async (ctx, res) => {
  let sql = 'select * from address'
  let saleList = await ctx.db.EXCUTE(sql);
  ctx.body = { List: saleList };
})

// 后台：地址信息分页查询
router.post('/pageAddress', async (ctx, res) => {
  let user = ctx.request.body;
  // console.log(user);
  let message = {};
  let pageNo = user.page || 1;
  let pageCount = user.pageSize || 10;
  let pageSize = pageCount;
  let page = (pageNo - 1) * pageCount;
  console.log(page, pageSize);
  let sql = `select * from address limit ${page},${pageSize}`;
  let results = await ctx.db.EXCUTE(sql)
  if (results == 0) {
    message = { code: 400, message: "获取分页数据失败" };
  } else {
    // console.log(results);
    message = { code: 200, message: '获取分页数据成功', List: results }
  }
  ctx.body = message
})

// 后台：查询显示地址信息信息
router.post('/putAddress', async (ctx, next) => {
  let sql = 'select * from address'
  let addressList = await ctx.db.EXCUTE(sql);
  ctx.body = { List: addressList };
})

// 后台：查询准确地址信息
router.post('/selAddress', async (ctx, next) => {
  let address = ctx.request.body
  let { userName } = address
  console.log(address);
  let sql = 'select * from address where userName = ?'
  let result = await ctx.db.EXCUTE(sql, [userName])
  console.log(result);
  if (result.length == 0) {
    message = { code: 400 }
  }
  else {
    message = { code: 200, List: result }
  }
  ctx.body = message;
})

// 后台：增加地址信息
router.post('/addAddress', async (ctx, next) => {
  let address = ctx.request.body
  let sql1 = 'select * from address where userName = ?and addressName=?'
  let sql2 = 'insert into address (userName,addressName,phoneNum,park,building) value (?,?,?,?,?)'
  let result = await ctx.db.EXCUTE(sql1, [address.userName, address.addressName])
  // console.log(result);
  if (result.length > 0) {
    message = { code: 400 }
  }
  else {
    await ctx.db.EXCUTE(sql2, [address.userName, address.addressName, address.phoneNum, address.park, address.building])
    message = { code: 200 }
  }
  ctx.body = message;
})

// 后台：删除地址信息
router.post('/delAddress', async (ctx, next) => {
  let address = ctx.request.body
  console.log(address);
  let { addressId } = address;
  let message = {}
  let sql1 = 'select * from address where addressId=?'
  let sql = 'delete from address where addressId=?'
  let result = await ctx.db.EXCUTE(sql1, [addressId])
  console.log(result);
  if (result.length == 0) {
    message = { code: 401 }
  }
  else {
    await ctx.db.EXCUTE(sql, [addressId], async (err, data) => {
      console.log(data);
      if (err) {
        message = { code: 400 }
      }
      if (data.affectedRows > 0) {
        message = { code: 200 }
      }
      else { message = { code: 202 } }
    })
  }
  ctx.body = message
})

// 后台：修改地址信息
router.post('/editAddress', async (ctx, next) => {
  let address = ctx.request.body
  let { userName, addressName, phoneNum, park, building, addressId } = address
  console.log(address);
  let sql1 = 'select * from address where addressId = ?'
  let sql2 = 'update address set userName=?,addressName=?, phoneNum=?,park=?,building=? where addressId=?'
  let result = await ctx.db.EXCUTE(sql1, [saleId])
  console.log(result);
  if (result.length == 0) {
    message = { code: 400 }
  }
  else {
    let results = await ctx.db.EXCUTE(sql2, [userName, addressName, phoneNum, park, building, addressId])
    message = { code: 200, List: results }
    console.log(results)
  }
  ctx.body = message;
})

// 后台：获取评论信息分页
router.post('/getPinglunData', async (ctx, res) => {
  let sql = 'select * from pinglun'
  let usersList = await ctx.db.EXCUTE(sql);
  console.log(usersList);
  ctx.body = { List: usersList };
})

// 用户分页
router.post('/pagePinglun', async (ctx, next) => {
  let user = ctx.request.body;
  console.log(user);
  let pageNo = user.page || 1;
  let pageCount = user.pageSize || 10;
  let pageSize = pageCount;
  let message = {};
  let page = (pageNo - 1) * pageCount;
  // console.log(page,pageSize);
  let sql = `select * from pinglun limit ${page},${pageSize}`;
  let results = await ctx.db.EXCUTE(sql)
  if (results == 0) {
    message = { code: 400, message: "获取分页数据失败" };
  } else {
    // console.log(results);
    message = { code: 200, message: '获取分页数据成功', List: results }
  }
  ctx.body = message;
})
// 后台：查询显示评论信息信息
router.post('/putPinglun', async (ctx, next) => {
  let sql = 'select * from pinglun'
  let pinglunList = await ctx.db.EXCUTE(sql);
  ctx.body = { List: pinglunList };
})

// 后台：查询准确评论信息
router.post('/selPinglun', async (ctx, next) => {
  let pinglun = ctx.request.body
  let { userName } = pinglun
  console.log(pinglun);
  let sql = 'select * from pinglun where userName = ?'
  let result = await ctx.db.EXCUTE(sql, [userName])
  console.log(result);
  if (result.length == 0) {
    message = { code: 400 }
  }
  else {
    message = { code: 200, List: result }
  }
  ctx.body = message;
})

// 后台：增加评论信息
router.post('/addPinglun', async (ctx, next) => {
  let pinglun1 = ctx.request.body
  let { userName, pinglunName, pinglunDate, pinglun } = pinglun1
  console.log(pinglun1);
  let sql1 = 'select * from pinglun where userName = ?'
  let sql2 = 'insert into pinglun (userName,pinglunName, pinglunDate, pinglun) value (?,?,?,?)'
  let result = await ctx.db.EXCUTE(sql1, [userName])
  console.log(result);
  if (result.length > 0) {
    message = { code: 400 }
  }
  else {
    await ctx.db.EXCUTE(sql2, [userName, pinglunName, pinglunDate, pinglun])
    message = { code: 200 }
  }
  ctx.body = message;
})

// 后台：删除评论信息
router.post('/delPinglun', async (ctx, next) => {
  let pinglun = ctx.request.body
  console.log(pinglun);
  let { userName, pinglunName } = pinglun;
  let message = {}
  let sql1 = 'select * from pinglun where userName=? and pinglunName=?'
  let sql = 'delete from pinglun where userName=? and pinglunName=?'
  let result = await ctx.db.EXCUTE(sql1, [userName, pinglunName])
  console.log(result);
  if (result.length == 0) {
    message = { code: 401 }
  }
  else {
    await ctx.db.EXCUTE(sql, [userName, pinglunName], async (err, data) => {
      console.log(data);
      if (err) {
        message = { code: 400 }
      }
      if (data.affectedRows > 0) {
        message = { code: 200 }
      }
      else { message = { code: 202 } }
    })
  }
  ctx.body = message
})

// 后台：修改评论信息
router.post('/editPinglun', async (ctx, next) => {
  let pinglun1 = ctx.request.body
  let { userName, pinglunName, pingDate, pinglun, pinglunId } = pinglun1
  console.log(pinglun1);
  let sql1 = 'select * from pinglun where pinglunId = ?'
  let sql2 = 'update pinglun set userName=?,pinglunName=?, pinglunDate=?,pinglun=? where pinglunId=?'
  let result = await ctx.db.EXCUTE(sql1, [pinglunId])
  console.log(result);
  if (result.length == 0) {
    message = { code: 400 }
  }
  else {
    let results = await ctx.db.EXCUTE(sql2, [userName, pinglunName, pingDate, pinglun, pinglunId])
    message = { code: 200, List: results }
    console.log(results)
  }
  ctx.body = message;
})


router.get('/', async (ctx, next) => {
  await ctx.render('index', {
    title: 'Hello Koa 2!'
  })
})
router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
})

router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router
